import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import css from './runtime.less'
import { Tabs } from 'antd'

function EditRender({ env, data, inputs, outputs, slots, style: initStyle }: any) {
  let cc = Number(data.colCount)
  let rc = Number(data.rowCount)
  const items: any = []
  for (let r = 1; r <= rc; r++) {
    for (let c = 1; c <= cc; c++) {
      const id = `_${r}_${c}`
      let start = (c - 1) * 2 + 1
      let end = start + 2
      if (r % 2 == 0) {
        start += 1
        end = start + 2
        if (end > cc * 2) continue
      }
      items.push(<div style={{ gridColumn: `${start} / ${end}`, overflow: 'visible' }}>{slots?.[id]?.render?.()}</div>)
    }
  }
  return (
    <div
      className={css['box']}
      style={{
        ...(data.style || {}),
        width: initStyle.width,
        height: initStyle.height,
        display: 'grid',
        gridTemplateColumns: `repeat(${cc * 2}, 1fr)`,
        gridTemplateRows: `repeat(${rc},1fr)`
      }}
    >
      {items}
    </div>
  )
}

function RuntimeRender({ env, data, inputs, outputs, slots, style: initStyle }: any) {
  const containerRef = useRef<HTMLDivElement>(null)
  const [style, setStyle] = useState(data.style || {})
  inputs['setStyle']((val, relOutput) => {
    const container = containerRef.current
    if (container) {
      if (val) {
        for (const [k, v] of Object.entries<string>(val)) {
          if (k.startsWith('--')) {
            container.style.setProperty(k, v)
          } else {
            container.style[k] = v
          }
        }
      }
    }
    relOutput['setStyleDone'](val)
  })
  inputs['getStyle']((val, relOutput) => {
    let style = {}
    const container = containerRef.current
    if (container) {
      style = container.style
    }
    relOutput['getStyleDone'](style)
  })
  let cc = Number(data.colCount)
  let rc = Number(data.rowCount)
  const items: any = []
  for (let r = 1; r <= rc; r++) {
    for (let c = 1; c <= cc; c++) {
      const id = `_${r}_${c}`
      let start = (c - 1) * 2 + 1
      let end = start + 2
      if (r % 2 == 0) {
        start += 1
        end = start + 2
        if (end > cc * 2) continue
      }
      items.push(<div style={{ gridColumn: `${start} / ${end}`, overflow: 'visible' }}>{slots?.[id]?.render?.()}</div>)
    }
  }
  return (
    <div
      className={css['box']}
      ref={containerRef}
      style={{
        ...(style || {}),
        width: initStyle.width,
        height: initStyle.height,
        display: 'grid',
        gridTemplateColumns: `repeat(${cc * 2}, 1fr)`,
        gridTemplateRows: `repeat(${rc},1fr)`
      }}
    >
      {items}
    </div>
  )
}

export default function (props: any) {
  /** 运行时 */
  return props.env?.edit ? <EditRender {...props} /> : <RuntimeRender {...props} />
}
